const cloud = require('wx-server-sdk')
wx.cloud.init({
  env: 'cloud1-5gigqqu3da01a065',
  traceUser: true
})

const db = cloud.database()
const notesCollection = db.collection('notes')

exports.main = async (event, context) => {
  const { action, data, noteId } = event
  
  try {
    switch (action) {
      case 'add':
        return await notesCollection.add({ data })
      case 'get':
        return await notesCollection.doc(noteId).get()
      case 'list':
        return await notesCollection.orderBy('id').get()
      case 'update':
        return await notesCollection.doc(noteId).update({ data })
      case 'delete':
        return await notesCollection.doc(noteId).remove()
      default:
        return { error: 'Invalid action' }
    }
  } catch (e) {
    return { error: e.message }
  }
}